package com.iqiyi.pps.epg.core.dao.base;

import com.iqiyi.kiwi.utils.ReflectionUtils;
import org.hibernate.event.PreInsertEvent;
import org.hibernate.event.PreInsertEventListener;
import org.hibernate.event.PreUpdateEvent;
import org.hibernate.event.PreUpdateEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;

/**
 * Created by IntelliJ IDEA.
 * User: lishunlong
 * Date: 12-6-6
 * Time: 上午10:03
 * To change this template use File | Settings | File Templates.
 */
public class DefaultEntityListener implements PreUpdateEventListener, PreInsertEventListener{
    private static Logger logger = LoggerFactory.getLogger(DefaultEntityListener.class);
    /**
     * Return true if the operation should be vetoed
     */

    @Override
    public boolean onPreUpdate(PreUpdateEvent event) {
        String[] names = event.getPersister().getPropertyNames();
        String updateTimeFieldName = "updateTime";

        for ( int i=0; i<names.length; i++) {
            if (updateTimeFieldName.equals(names[i])) {
                try {
                    Timestamp timestamp = new Timestamp(System.currentTimeMillis());
                    event.getState()[i] = timestamp;
                    ReflectionUtils.invokeSetterMethod(event.getEntity(), updateTimeFieldName, timestamp);
                } catch (Exception e) {
                    logger.error(e.toString(), e);
                }
                break;
            }
        }
        return false;
    }

    /**
     * Return true if the operation should be vetoed
     */
    @Override
    public boolean onPreInsert(PreInsertEvent event) {
        String createTimeFieldName = "createTime";
        try {
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            ReflectionUtils.invokeSetterMethod(event.getEntity(), createTimeFieldName, timestamp);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return false;
    }
}
